package cn.tedu.demo.config;


import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

//方案2：在过滤器的层面实现跨域配置
//@Configuration
public class CorsFilterConfig {
    @Bean
    public FilterRegistrationBean<CorsFilter> filterFilterRegistrationBean(){
        UrlBasedCorsConfigurationSource configSource=new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        //是否携带cookie跨域
        config.setAllowCredentials(true);
        configSource.registerCorsConfiguration("/**",config);
        FilterRegistrationBean<CorsFilter> fBean=new FilterRegistrationBean<>(new CorsFilter(configSource));
        //参数表示这个过滤器在众多过滤器中级别最高，也就是过滤的时候最先执行
        fBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return fBean;
    }
}
